/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dorian.atomicuml.dao;

import com.dorian.atomicuml.dao.interfaces.ProjectManager;
import com.dorian.atomicuml.orm.Projects;
import java.sql.Timestamp;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Ayden
 */
public class ProjectManagerImpl implements ProjectManager {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @Override
    public Projects getProject(int id) {
        Session session = sessionFactory.getCurrentSession();
        
        Query findProject = session.getNamedQuery("Projects.findById")
                                   .setParameter("id", id);
        Projects p = (Projects) findProject.uniqueResult();
        return p;
    }

    
    @Override
    public void createProject(String title, String description, Integer ownerId) throws Exception {
        Session session = sessionFactory.getCurrentSession();
        
        Query findProject = session.getNamedQuery("Projects.findByTitle")
                                   .setParameter("title", title);
        
        Projects findp = (Projects) findProject.uniqueResult();
        
        if (!(findp != null)) {
            Timestamp date = new Timestamp(System.currentTimeMillis());
            Projects p = new Projects(0, title, description, date, date, ownerId);
            session.save(p); 
        }
        else
            throw new Exception("This project already exist.");
    }

    @Override
    public void updateProject(Projects project) {
        Timestamp date = new Timestamp(System.currentTimeMillis());
        Session session = sessionFactory.getCurrentSession();

        project.setDatemodif(date);
        
        session.saveOrUpdate(project);
    }

    @Override
    public boolean deleteProject(int ProjectId) throws Exception {
        Session session = sessionFactory.getCurrentSession();
        
        Query query = session.getNamedQuery("Projects.findById")
                             .setParameter("id", ProjectId);
                        
        Projects p = (Projects) query.uniqueResult();
        try
        {
            session.delete(p);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return false;
        }
        return true;
    }
}
